package com.ibiaoke.marketing.dao;

import com.ibiaoke.common.base.BaseDao;
import com.ibiaoke.common.base.Page;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.marketing.entity.Coupon;
import com.ibiaoke.marketing.entity.CouponExample;
import com.ibiaoke.marketing.mapper.CouponMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * Created by huhaichao on 2017/6/14.
 */
@Repository
public class CouponDao extends BaseDao<Coupon, CouponExample, Integer, CouponMapper> {

    @Autowired
    private CouponMapper couponMapper;

    @Override
    public CouponMapper getMapper() {
        return couponMapper;
    }

    public int deleteCoupon(Integer couponId) {
        Coupon coupon = new Coupon();
        coupon.setCouponId(couponId);
        coupon.setDelStatus((byte) CommonConsts.YES);
        return updateByPrimaryKeySelective(coupon);
    }

    public List<Coupon> listCoupon(String couponName, Integer useType,Date beginTime, Date endTime, Page page) {

        CouponExample example = new CouponExample();
        CouponExample.Criteria criteria = example.createCriteria();
        if(useType != null) {
            criteria.andUseTypeEqualTo(useType);
        }
        if (StringUtils.isNotBlank(couponName)) {
            criteria.andCouponNameEqualTo(couponName);
        }
        if (beginTime != null) {
            criteria.andReceiveBeginTimeGreaterThan(beginTime);
        }
        if (endTime != null) {
            criteria.andReceiveBeginTimeLessThan(endTime);
        }
        criteria.andDelStatusEqualTo((byte)CommonConsts.NO);
        page.setTotalCount(countByExample(example));
        example.setLimitStart(page.limitStart());
        example.setLimitEnd(page.limitEnd());

        return selectByExample(example);
    }

    public Coupon getCoupon(String couponCode) {
        CouponExample example = new CouponExample();
        example.createCriteria().andCouponCodeEqualTo(couponCode).andDelStatusEqualTo((byte) CommonConsts.NO);
        return getByExample(example);
    }

    public List<Coupon> listCoupon(String couponGroup) {
        CouponExample example = new CouponExample();
        example.createCriteria().andCouponGroupEqualTo(couponGroup).andDelStatusEqualTo((byte) CommonConsts.NO);
        return selectByExample(example);
    }

    public Coupon getCouponById(Integer id){
        CouponExample example = new CouponExample();
        example.createCriteria().andCouponIdEqualTo(id).andDelStatusEqualTo((byte) CommonConsts.NO);
        return getByExample(example);
    }

    public void updateTotalCount(Coupon coupon,Integer totalCount){
        coupon.setTotalCount(totalCount);
        updateByPrimaryKeySelective(coupon);
    }
}
